package xyz.coolcsm.security.controller;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.*;
import xyz.coolcsm.security.config.JsonResult;
import xyz.coolcsm.security.config.ResultCode;
import xyz.coolcsm.security.config.ResultTool;
import xyz.coolcsm.security.config.RsaKeyProperties;
import xyz.coolcsm.security.entity.Payload;
import xyz.coolcsm.security.entity.SysUser;
import xyz.coolcsm.security.service.RedisService;
import xyz.coolcsm.security.service.SysUserService;
import xyz.coolcsm.security.utils.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
 * @author 什锦
 * @since 2021-06-1
 */

@RestController
public class LoginController {
    @Autowired
    SysUserService sysUserService;

    @Autowired
    JavaMailSenderImpl mailSender;

    @Autowired
    private RsaKeyProperties prop;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisService redisService;

    //注册账号
    @PostMapping("/api/register")
    public JsonResult register(HttpServletRequest request,@RequestBody SysUser user) {
        String code = (String)redisService.get(user.getEmail());
        redisService.del(user.getEmail());
        if (code != user.getCode()) {
            return ResultTool.fail();
        }
        SysUser insert = sysUserService.insert(user);
        return ResultTool.success(insert);
    }

    //验证邮箱发送
    @PostMapping("/api/mail")
    public JsonResult sendMail(HttpServletRequest request, @RequestBody String mail){
        Map<String,String> map= (Map<String, String>) JSONObject.toBean(JSONObject.fromObject(mail), Map.class);
        mail = map.get("mail");
        MailUtils.setMailSender(mailSender);
        String checkCode = CodeUtil.getCheckCode();
        redisService.set(mail,checkCode,5*60*60);
        try {
            MailUtils.sendMail(mail,mail+"正在进行登陆，验证码:"+checkCode+",5分钟内有效。如非本人操作，请忽略。。","登陆验证");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultTool.fail();
        }
        return ResultTool.success();
    }

    //验证账号是否存在，确保账号唯一性
    @PostMapping("/api/exist")
    public JsonResult exist(@RequestBody SysUser user){
        SysUser sysUser = sysUserService.selectByName(user.getUsername());
        if (sysUser == null){
            return ResultTool.success();
        }
        return ResultTool.fail();
    }

    //验证账号是否登陆
    @GetMapping(value = "/api/authentication")
    public JsonResult authentication(HttpServletRequest request){
        String headerToken=request.getHeader("Authorization");
        try {
            Payload<SysUser> payload = JwtUtils.getInfoFromToken(headerToken.replace("Bearer ", ""),
                    prop.getPublicKey(), SysUser.class);
            Object o = redisService.get(payload.getUserInfo().getId().toString());
            if (o==null){
                return ResultTool.fail();
            }
        } catch (Exception e) {
            return ResultTool.fail(ResultCode.USER_NOT_LOGIN);
        }
        return ResultTool.success();
    }

    //退出登陆
    @GetMapping("/api/logout")
    public JsonResult logout(HttpServletRequest request){
        String headerToken=request.getHeader("Authorization");
        Payload<SysUser> payload = JwtUtils.getInfoFromToken(headerToken.replace("Bearer ", ""),
                prop.getPublicKey(), SysUser.class);
        Boolean del = redisService.del(payload.getUserInfo().getId().toString());
        if (del == false){
            return ResultTool.fail();
        }
        return ResultTool.success();
    }


    @GetMapping("/api/getCode")
    public JsonResult getCode(){
        Map<String, Object> resultMap = new HashMap<>();
        ImageUtil.createImage("http://localhost:8080/api/file/a6.jpg",resultMap);
        String uuid = UUIDUtils.getUuid();
        int xWidth = Integer.valueOf(resultMap.get("xWidth").toString());
        resultMap.remove("xWidth");
        resultMap.put("uuid",uuid);
        redisService.set(uuid,xWidth,60);
        return ResultTool.success(resultMap);
    }

    @GetMapping("/api/checkCode/{left}/{uuid}")
    public JsonResult checkCode(@PathVariable("left") Integer left,@PathVariable("uuid") String uuid){
        Integer o = (Integer)redisService.get(uuid);
        if (left<=o-8 || o+8<=left){
            return ResultTool.fail();
        }
        return ResultTool.success();
    }

}
